/*
 * @(#)Base62.java   1.0  2022年4月13日
 * 
 * Copyright (c)	2014-2020. All Rights Reserved.	GuangZhou hhmk Technology Company LTD.
 */
package com.swift.util.type;

import org.apache.commons.lang3.StringUtils;

/**
 * Base62进制
 * 
 * @author zhengjiajin
 * @version 1.0 2022年4月13日
 */
public class Base62 {

    private static final String chars = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    private static final int DEF_LENGTH = 6;
    
    public static String encode(long num) {
        return encode(num, DEF_LENGTH);
    }

    public static String encode(long num,Integer length) {
        if (length==null || length==0) { length=DEF_LENGTH; }
        StringBuilder sb = new StringBuilder();
        int remainder = 0;
        int scale = 62;
        while (num > scale - 1) {
            remainder = Long.valueOf(num % scale).intValue();
            sb.append(chars.charAt(remainder));
            num = num / scale;
        }
        sb.append(chars.charAt(Long.valueOf(num).intValue()));
        String value = sb.reverse().toString();
        return StringUtils.leftPad(value, length, '0');
    }

    public static long decode(String str) {
        int scale = 62;
        str = str.replace("^0*", "");
        long num = 0;
        int index = 0;
        for (int i = 0; i < str.length(); i++) {
            index = chars.indexOf(str.charAt(i));
            num += (long) (index * (Math.pow(scale, str.length() - i - 1)));
        }
        return num;
    }

}
